<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语义相似度分析API管理界面</title>
    <script src="/static/tailwindcss.js"></script>
    <link href="/static/full.min.css" rel="stylesheet" type="text/css" />
    <link href="/static/all.min.css" rel="stylesheet">
    <style>
        .result-card {
            transition: all 0.3s ease;
        }
        .result-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }
        .json-viewer {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 16px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
        }
        .loading-spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-right: 8px;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }

        .result-card {
        transition: all 0.3s ease;
    }
    .result-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.1);
    }
    .json-viewer {
        background: #f8fafc;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        padding: 16px;
        font-family: 'Courier New', monospace;
        font-size: 14px;
        white-space: pre-wrap;
        max-height: 400px;
        overflow-y: auto;
    }
    .loading-spinner {
        border: 3px solid #f3f3f3;
        border-top: 3px solid #3498db;
        border-radius: 50%;
        width: 20px;
        height: 20px;
        animation: spin 1s linear infinite;
        display: inline-block;
        margin-right: 8px;
    }
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    .tab-content {
        display: none;
    }
    .tab-content.active {
        display: block;
    }

    /* 自定义导航按钮选中状态样式 */
    .tab-btn.btn-active {
        background-color: rgba(255, 255, 255, 0.2) !important;
        color: #ffffff !important;
        font-weight: 600;
        border: 1px solid rgba(255, 255, 255, 0.3);
    }

    .tab-btn:hover {
        background-color: rgba(255, 255, 255, 0.1);
        color: #ffffff;
    }
    </style>
</head>
<body class="bg-base-200 min-h-screen">
    <!-- 导航栏 -->
    <div class="navbar bg-primary text-primary-content shadow-lg">
        <div class="navbar-start">
            <div class="dropdown">
                <div tabindex="0" role="button" class="btn btn-ghost lg:hidden">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h8m-8 6h16"></path>
                    </svg>
                </div>
                <ul tabindex="0" class="menu menu-sm dropdown-content mt-3 z-[1] p-2 shadow bg-base-100 rounded-box w-52">
                    <li><a onclick="showTab('search')">语义搜索</a></li>
                    <li><a onclick="showTab('management')">数据管理</a></li>
                    <li><a onclick="showTab('system')">系统管理</a></li>
                    <li><a onclick="showTab('settings')">配置管理</a></li>
                </ul>
            </div>
            <a class="btn btn-ghost text-xl">
                <i class="fas fa-brain mr-2"></i>
                语义相似度分析API
            </a>
        </div>
        <div class="navbar-center hidden lg:flex">
            <ul class="menu menu-horizontal px-1">
                <li><a onclick="showTab('search')" class="tab-btn" data-tab="search">
                    <i class="fas fa-search mr-2"></i>语义搜索
                </a></li>
                <li><a onclick="showTab('management')" class="tab-btn" data-tab="management">
                    <i class="fas fa-database mr-2"></i>数据管理
                </a></li>
                <li><a onclick="showTab('system')" class="tab-btn" data-tab="system">
                    <i class="fas fa-cogs mr-2"></i>系统管理
                </a></li>
                <li><a onclick="showTab('settings')" class="tab-btn" data-tab="settings">
                    <i class="fas fa-sliders-h mr-2"></i>配置管理
                </a></li>
            </ul>
        </div>
        <div class="navbar-end">
            <label class="swap swap-rotate btn btn-ghost btn-circle">
                <input type="checkbox" class="theme-controller" value="dark" />
                <svg class="swap-off fill-current w-6 h-6" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <path d="M21,13V11H19V13H21M20,4H18L18,6H16L16,4H14L14,2H10L10,4H8L8,6H6L6,4H4L4,6H2V8H4V10H2V12H4V14H2V16H4V18H6V16H8V18H10V16H12V18H14V16H16V18H18V16H20V14H22V12H20V10H22V8H20V6Z"/>
                </svg>
                <svg class="swap-on fill-current w-6 h-6" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <path d="M17,12A5,5 0 0,1 12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7A5,5 0 0,1 17,12M12,1L15.39,6.39L20.36,4.64L18.61,9.61L23.58,11.36L18.61,13.11L20.36,18.08L15.39,16.33L12,21.72L8.61,16.33L3.64,18.08L5.39,13.11L0.42,11.36L5.39,9.61L3.64,4.64L8.61,6.39L12,1Z"/>
                </svg>
            </label>
        </div>
    </div>

    <!-- API基础配置 -->
    <div class="container mx-auto p-4">
        <div class="card bg-base-100 shadow-xl mb-6">
            <div class="card-body">
                <h2 class="card-title">
                    <i class="fas fa-server mr-2"></i>API配置
                </h2>
                <div class="form-control">
                    <label class="label">
                        <span class="label-text">API基础URL</span>
                    </label>
                    <input type="url" id="apiBaseUrl" placeholder="http://10.243.165.54:12000"
                           value="http://10.243.165.54:12000" class="input input-bordered">
                </div>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div id="content-area">
            <!-- 语义搜索模块 -->
            <div id="search-tab" class="tab-content active">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <!-- 单次搜索 -->
                    <div class="card bg-base-100 shadow-xl">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-search mr-2"></i>单次语义搜索
                            </h2>
                            <form id="searchForm" class="space-y-4">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">查询文本 *</span>
                                    </label>
                                    <textarea class="textarea textarea-bordered" id="queryText"
                                            placeholder="请输入要搜索的文本内容..." rows="3" required></textarea>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">查询类型 *</span>
                                    </label>
                                    <select class="select select-bordered" id="queryType" required>
                                        <option value="">请选择查询类型</option>
                                        <option value="功能用户需求">功能用户需求</option>
                                        <option value="功能过程">功能过程</option>
                                        <option value="子过程描述">子过程描述</option>
                                    </select>
                                </div>
                                <div class="grid grid-cols-2 gap-4">
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">返回结果数</span>
                                        </label>
                                        <input type="number" class="input input-bordered" id="topK"
                                               value="10" min="1" max="100">
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">Cosmic ID</span>
                                        </label>
                                        <input type="text" class="input input-bordered" id="cosmicId"
                                               placeholder="可选过滤条件">
                                    </div>
                                </div>
                                <div class="grid grid-cols-2 gap-4">
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">合同编码</span>
                                        </label>
                                        <input type="text" class="input input-bordered" id="contractCode"
                                               placeholder="可选过滤条件">
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">厂商编码</span>
                                        </label>
                                        <input type="text" class="input input-bordered" id="firmCode"
                                               placeholder="可选过滤条件">
                                    </div>
                                </div>
                                <div class="card-actions justify-end">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search mr-2"></i>搜索
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 批量搜索 -->
                    <div class="card bg-base-100 shadow-xl">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-list mr-2"></i>批量语义搜索
                            </h2>
                            <form id="batchSearchForm" class="space-y-4">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">批量查询配置</span>
                                        <span class="label-text-alt">JSON格式</span>
                                    </label>
                                    <textarea class="textarea textarea-bordered font-mono" id="batchQueries"
                                            rows="8" placeholder='[\n  {\n    "query_text": "用户登录功能",\n    "query_type": "功能用户需求",\n    "top_k": 5\n  },\n  {\n    "query_text": "数据处理流程",\n    "query_type": "功能过程",\n    "top_k": 3\n  }\n]'></textarea>
                                </div>
                                <div class="card-actions justify-end">
                                    <button type="button" onclick="formatBatchJson()" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-code mr-2"></i>格式化JSON
                                    </button>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-play mr-2"></i>批量搜索
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <!-- Cosmic相似度分析 -->
                    <div class="card bg-base-100 shadow-xl">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-chart-line mr-2"></i>pswfinstid相似度分析
                            </h2>
                            <form id="cosmicAnalysisForm" class="space-y-4">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">pswfinstid *</span>
                                    </label>
                                    <input type="text" class="input input-bordered" id="analysisCosmicId"
                                           placeholder="请输入要分析的pswfinstid" required>
                                </div>
                                <div class="alert alert-info">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current shrink-0 w-6 h-6">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                    </svg>
                                    <span>分析指定pswfinstid的相似度数据和相关信息</span>
                                </div>
                                <div class="card-actions justify-end">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-chart-line mr-2"></i>开始分析
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 内部相似度分析 -->
                    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                        <div class="flex items-center mb-4">
                            <i class="fas fa-search-plus mr-2 text-purple-600"></i>
                            <h2 class="text-xl font-semibold text-gray-800">多字段内部相似度分析</h2>
                        </div>

                        <form id="multiFieldSimilarityForm" class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="multiFieldCosmicId" class="block text-sm font-medium text-gray-700 mb-2">
                                        Cosmic ID
                                    </label>
                                    <input type="text" id="multiFieldCosmicId" name="cosmicId"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500"
                                           placeholder="请输入Cosmic ID" required>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">
                                        分析字段
                                    </label>
                                    <div class="space-y-2">
                                        <label class="flex items-center">
                                            <input type="checkbox" id="field_gnyhxq" value="gnyhxq" checked
                                                   class="mr-2 text-purple-600 focus:ring-purple-500">
                                            <span class="text-sm">gnyhxq (功能用户需求)</span>
                                        </label>
                                        <label class="flex items-center">
                                            <input type="checkbox" id="field_gngc" value="gngc" checked
                                                   class="mr-2 text-purple-600 focus:ring-purple-500">
                                            <span class="text-sm">gngc (功能过程)</span>
                                        </label>
                                        <label class="flex items-center">
                                            <input type="checkbox" id="field_zgcms" value="zgcms" checked
                                                   class="mr-2 text-purple-600 focus:ring-purple-500">
                                            <span class="text-sm">zgcms (子过程描述)</span>
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="bg-blue-50 border-l-4 border-blue-400 p-4">
                                <div class="flex">
                                    <div class="flex-shrink-0">
                                        <i class="fas fa-info-circle text-blue-400"></i>
                                    </div>
                                    <div class="ml-3">
                                        <p class="text-sm text-blue-700">
                                            <span class="font-medium">功能说明：</span>
                                            分析指定Cosmic ID中选定字段去重后每个内容之间的相似度，使用配置的阈值检查是否有超过阈值的相似内容对
                                        </p>
                                        <p class="text-xs text-blue-600 mt-1">
                                            阈值配置：功能用户需求(80%), 功能过程(80%), 子过程描述(80%)
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <button type="submit"
                                    class="w-full bg-purple-600 text-white py-2 px-4 rounded-md hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 transition duration-200">
                                <i class="fas fa-play mr-2"></i>开始分析
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- 数据管理模块 -->
            <div id="management-tab" class="tab-content">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <!-- 更新数据 -->
                    <div class="card bg-base-100 shadow-xl">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-edit mr-2"></i>更新数据
                            </h2>
                            <form id="updateForm" class="space-y-4">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">数据ID *</span>
                                    </label>
                                    <input type="text" class="input input-bordered" id="updateDataId"
                                           placeholder="要更新的数据ID" required>
                                </div>
                                <div class="grid grid-cols-2 gap-4">
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">Cosmic ID *</span>
                                        </label>
                                        <input type="text" class="input input-bordered" id="updateCosmicId" required>
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">厂商编码 *</span>
                                        </label>
                                        <input type="text" class="input input-bordered" id="updateFirmCode" required>
                                    </div>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">合同编码 *</span>
                                    </label>
                                    <input type="text" class="input input-bordered" id="updateContractCode" required>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">功能用户需求</span>
                                    </label>
                                    <textarea class="textarea textarea-bordered" id="updateGnyhxq" rows="3"></textarea>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">功能过程</span>
                                    </label>
                                    <textarea class="textarea textarea-bordered" id="updateGngc" rows="3"></textarea>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">子过程描述</span>
                                    </label>
                                    <textarea class="textarea textarea-bordered" id="updateZgcms" rows="3"></textarea>
                                </div>
                                <div class="card-actions justify-end">
                                    <button type="submit" class="btn btn-warning">
                                        <i class="fas fa-save mr-2"></i>更新数据
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 删除数据 -->
                    <div class="card bg-base-100 shadow-xl">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-trash mr-2"></i>删除数据
                            </h2>
                            <form id="deleteForm" class="space-y-4">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">CosmicID列表 *</span>
                                        <span class="label-text-alt">每行一个CosmicID</span>
                                    </label>
                                    <textarea class="textarea textarea-bordered" id="deleteDataIds"
                                            placeholder="请输入要删除的CosmicID，每行一个：&#10;12345&#10;12346&#10;12347"
                                            rows="8" required></textarea>
                                </div>
                                <div class="alert alert-warning">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                                    </svg>
                                    <span>删除操作不可撤销，请谨慎操作！</span>
                                </div>
                                <div class="card-actions justify-end">
                                    <button type="submit" class="btn btn-error">
                                        <i class="fas fa-trash mr-2"></i>删除数据
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 批量更新 -->
                    <div class="card bg-base-100 shadow-xl lg:col-span-2">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-upload mr-2"></i>批量更新数据
                            </h2>
                            <form id="batchUpdateForm" class="space-y-4">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">批量更新数据</span>
                                        <span class="label-text-alt">JSON格式</span>
                                    </label>
                                    <textarea class="textarea textarea-bordered font-mono" id="batchUpdateData"
                                            rows="10" placeholder='[\n  {\n    "data_id": "12345",\n    "cosmicid": "COSMIC001",\n    "firmcode": "FIRM001",\n    "contract_code": "CONTRACT001",\n    "gnyhxq": "用户登录功能需求",\n    "gngc": "登录验证过程",\n    "zgcms": "密码验证子过程"\n  }\n]'></textarea>
                                </div>
                                <div class="card-actions justify-between">
                                    <button type="button" onclick="formatBatchUpdateJson()" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-code mr-2"></i>格式化JSON
                                    </button>
                                    <button type="submit" class="btn btn-warning">
                                        <i class="fas fa-upload mr-2"></i>批量更新
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 系统管理模块 -->
            <div id="system-tab" class="tab-content">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <!-- 系统状态 -->
                    <div class="card bg-base-100 shadow-xl">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-heartbeat mr-2"></i>系统状态检查
                            </h2>
                            <div id="systemStatus" class="mb-4">
                                <div class="text-center text-gray-500 py-4">
                                    <i class="fas fa-spinner fa-spin text-2xl mb-2"></i>
                                    <p>正在检查系统状态...</p>
                                </div>
                            </div>
                            <div class="card-actions justify-end">
                                <button onclick="checkSystemStatus()" class="btn btn-info">
                                    <i class="fas fa-sync mr-2"></i>刷新状态
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 增量更新 -->
                    <div class="card bg-base-100 shadow-xl">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-sync-alt mr-2"></i>增量更新
                            </h2>
                            <form id="incrementalUpdateForm" class="space-y-4">
                                <div class="alert alert-info">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current shrink-0 w-6 h-6">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                    </svg>
                                    <span>增量更新将从数据库获取新数据并更新索引</span>
                                </div>
                                <div class="card-actions justify-end">
                                    <button type="submit" class="btn btn-success">
                                        <i class="fas fa-sync-alt mr-2"></i>执行增量更新
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 系统初始化 -->
                    <div class="card bg-base-100 shadow-xl lg:col-span-2">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-rocket mr-2"></i>系统初始化
                            </h2>
                            <form id="initializeForm" class="space-y-4">
                                <div class="alert alert-warning">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                                    </svg>
                                    <div>
                                        <h3 class="font-bold">警告：系统初始化</h3>
                                        <div class="text-xs">此操作将清除所有缓存数据并重新构建索引，可能需要较长时间！</div>
                                    </div>
                                </div>
                                <div class="card-actions justify-end">
                                    <button type="submit" class="btn btn-error">
                                        <i class="fas fa-rocket mr-2"></i>重新初始化系统
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 自动更新定时器控制 -->
                    <div class="card bg-base-100 shadow-xl lg:col-span-2">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-clock mr-2"></i>自动更新定时器控制
                            </h2>

                            <!-- 定时器状态显示 -->
                            <div class="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-4">
                                <div class="stat bg-base-200 rounded-lg">
                                    <div class="stat-figure text-primary">
                                        <i class="fas fa-power-off text-2xl"></i>
                                    </div>
                                    <div class="stat-title">启用状态</div>
                                    <div class="stat-value text-lg" id="timerEnabledStatus">-</div>
                                </div>
                                <div class="stat bg-base-200 rounded-lg">
                                    <div class="stat-figure text-secondary">
                                        <i class="fas fa-play-circle text-2xl"></i>
                                    </div>
                                    <div class="stat-title">运行状态</div>
                                    <div class="stat-value text-lg" id="timerRunningStatus">-</div>
                                </div>
                                <div class="stat bg-base-200 rounded-lg">
                                    <div class="stat-figure text-accent">
                                        <i class="fas fa-stopwatch text-2xl"></i>
                                    </div>
                                    <div class="stat-title">更新间隔</div>
                                    <div class="stat-value text-lg" id="timerInterval">-</div>
                                </div>
                            </div>

                            <!-- 定时器配置表单 -->
                            <form id="timerConfigForm" class="space-y-4">
                                <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">启用定时器</span>
                                        </label>
                                        <label class="cursor-pointer label">
                                            <span class="label-text">自动执行增量更新</span>
                                            <input type="checkbox" id="timerEnabled" class="toggle toggle-primary" />
                                        </label>
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">更新间隔（秒）</span>
                                            <span class="label-text-alt">最小值: 60</span>
                                        </label>
                                        <input type="number" class="input input-bordered" id="timerIntervalInput"
                                               min="60" step="1" value="3600" placeholder="3600">
                                    </div>
                                </div>

                                <div class="alert alert-info">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current shrink-0 w-6 h-6">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                    </svg>
                                    <span>定时器将按设定间隔自动执行增量更新，建议间隔不少于60秒</span>
                                </div>

                                <div class="card-actions justify-between">
                                    <button type="button" id="refreshTimerStatusBtn" class="btn btn-outline">
                                        <i class="fas fa-sync-alt mr-2"></i>刷新状态
                                    </button>
                                    <div class="space-x-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save mr-2"></i>应用配置
                                        </button>
                                        <button type="button" id="startTimerBtn" class="btn btn-success">
                                            <i class="fas fa-play mr-2"></i>启动定时器
                                        </button>
                                        <button type="button" id="stopTimerBtn" class="btn btn-error">
                                            <i class="fas fa-stop mr-2"></i>停止定时器
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 配置管理模块 -->
            <div id="settings-tab" class="tab-content">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <!-- 相似度阈值设置 -->
                    <div class="card bg-base-100 shadow-xl">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-sliders-h mr-2"></i>相似度阈值设置
                            </h2>
                            <form id="thresholdForm" class="space-y-4">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">功能用户需求阈值</span>
                                        <span class="label-text-alt">0.0 - 1.0</span>
                                    </label>
                                    <input type="number" class="input input-bordered" id="thresholdGnyhxq"
                                           step="0.01" min="0" max="1" value="0.85">
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">功能过程阈值</span>
                                        <span class="label-text-alt">0.0 - 1.0</span>
                                    </label>
                                    <input type="number" class="input input-bordered" id="thresholdGngc"
                                           step="0.01" min="0" max="1" value="0.90">
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text">子过程描述阈值</span>
                                        <span class="label-text-alt">0.0 - 1.0</span>
                                    </label>
                                    <input type="number" class="input input-bordered" id="thresholdZgcms"
                                           step="0.01" min="0" max="1" value="0.88">
                                </div>
                                <div class="card-actions justify-end">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save mr-2"></i>更新阈值
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 当前配置显示 -->
                    <div class="card bg-base-100 shadow-xl">
                        <div class="card-body">
                            <h2 class="card-title">
                                <i class="fas fa-info-circle mr-2"></i>当前配置
                            </h2>
                            <div id="currentThresholds">
                                <div class="text-center text-gray-500 py-4">
                                    <i class="fas fa-spinner fa-spin text-2xl mb-2"></i>
                                    <p>正在加载配置...</p>
                                </div>
                            </div>
                            <div class="card-actions justify-end">
                                <button onclick="loadCurrentThresholds()" class="btn btn-secondary">
                                    <i class="fas fa-sync mr-2"></i>刷新配置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 结果显示区域 -->
        <div class="card bg-base-100 shadow-xl mt-6">
            <div class="card-body">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="card-title">
                        <i class="fas fa-chart-bar mr-2"></i>执行结果
                    </h2>
                    <div class="flex gap-2">
                        <button onclick="exportResults()" class="btn btn-outline btn-sm">
                            <i class="fas fa-download mr-2"></i>导出结果
                        </button>
                        <button onclick="clearResults()" class="btn btn-outline btn-sm">
                            <i class="fas fa-trash mr-2"></i>清空结果
                        </button>
                    </div>
                </div>
                <div id="results-content">
                    <div class="text-center text-gray-500 py-8">
                        <i class="fas fa-search text-4xl mb-4"></i>
                        <p>执行API调用后，结果将在这里显示</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loading-toast" class="toast toast-center hidden">
        <div class="alert alert-info">
            <div class="loading-spinner"></div>
            <span>正在处理请求...</span>
        </div>
    </div>

    <script>
        let currentResults = null;

        // 标签页切换
        function showTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });

            // 显示选中的标签页
            document.getElementById(tabName + '-tab').classList.add('active');

            // 更新导航栏样式
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('btn-active');
            });
            document.querySelector(`[data-tab="${tabName}"]`)?.classList.add('btn-active');
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('loading-toast').classList.remove('hidden');
        }

        // 隐藏加载状态
        function hideLoading() {
            document.getElementById('loading-toast').classList.add('hidden');
        }

        // 显示结果
        function showResults(data, title = '执行结果') {
            currentResults = data;
            const resultsContent = document.getElementById('results-content');

            if (Array.isArray(data) && data.length > 0 && data[0].results) {
                // 搜索结果显示
                let html = '';
                data.forEach((queryResult, index) => {
                    html += `
                        <div class="result-card mb-6 p-4 border rounded-lg">
                            <div class="flex justify-between items-start mb-4">
                                <h3 class="text-lg font-semibold">查询 ${index + 1}: ${queryResult.query_type}</h3>
                                <div class="badge badge-primary">${queryResult.total_count} 个结果</div>
                            </div>
                            <p class="text-gray-600 mb-4">${queryResult.query_text}</p>
                            <div class="grid gap-3">
                    `;

                    queryResult.results.forEach((result, idx) => {
                        const percentage = result.similarity_percentage.toFixed(2);
                        const badgeClass = percentage >= 90 ? 'badge-success' :
                                         percentage >= 70 ? 'badge-warning' : 'badge-error';

                        html += `
                            <div class="card bg-base-50 border">
                                <div class="card-body p-4">
                                    <div class="flex justify-between items-start mb-2">
                                        <h4 class="font-medium">结果 ${idx + 1}</h4>
                                        <span class="badge ${badgeClass}">${percentage}%</span>
                                    </div>
                                    <p class="text-sm text-gray-700 mb-2">${result.content}</p>
                                    <div class="flex flex-wrap gap-2 text-xs text-gray-500">
                                        <span>ID: ${result.data_id}</span>
                                        <span>Cosmic: ${result.cosmicid}</span>
                                        <span>厂商: ${result.firmcode}</span>
                                        <span>合同: ${result.contract_code}</span>
                                    </div>
                                </div>
                            </div>
                        `;
                    });

                    html += `
                            </div>
                            <div class="text-xs text-gray-500 mt-2">
                                执行时间: ${queryResult.execution_time.toFixed(3)}秒
                            </div>
                        </div>
                    `;
                });
                resultsContent.innerHTML = html;
            } else {
                // JSON结果显示
                resultsContent.innerHTML = `
                    <div class="json-viewer">
                        ${JSON.stringify(data, null, 2)}
                    </div>
                `;
            }
        }

        // 显示错误
        function showError(message) {
            const resultsContent = document.getElementById('results-content');
            resultsContent.innerHTML = `
                <div class="alert alert-error">
                    <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <span>错误: ${message}</span>
                </div>
            `;
        }

        // API调用函数
        async function apiCall(endpoint, method = 'GET', data = null) {
            const baseUrl = document.getElementById('apiBaseUrl').value.replace(/\/$/, '');
            const url = `${baseUrl}${endpoint}`;

            const options = {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                },
            };

            if (data) {
                options.body = JSON.stringify(data);
            }

            try {
                const response = await fetch(url, options);
                const result = await response.json();

                if (!response.ok) {
                    throw new Error(result.detail || `HTTP ${response.status}`);
                }

                return result;
            } catch (error) {
                console.error('API调用失败:', error);
                throw error;
            }
        }

        // 表单提交处理函数
        document.getElementById('searchForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            showLoading();

            try {
                const formData = {
                    query_text: document.getElementById('queryText').value,
                    query_type: document.getElementById('queryType').value,
                    top_k: parseInt(document.getElementById('topK').value) || 10
                };

                // 添加可选过滤条件
                const cosmicId = document.getElementById('cosmicId').value;
                const contractCode = document.getElementById('contractCode').value;
                const firmCode = document.getElementById('firmCode').value;

                if (cosmicId) formData.cosmicid = cosmicId;
                if (contractCode) formData.contract_code = contractCode;
                if (firmCode) formData.firmcode = firmCode;

                const result = await apiCall('/search', 'POST', formData);
                showResults([result], '语义搜索结果');
            } catch (error) {
                showError(error.message);
            } finally {
                hideLoading();
            }
        });

        document.getElementById('batchSearchForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            showLoading();

            try {
                const batchData = JSON.parse(document.getElementById('batchQueries').value);
                const result = await apiCall('/batch_search', 'POST', { queries: batchData });
                showResults(result, '批量搜索结果');
            } catch (error) {
                if (error instanceof SyntaxError) {
                    showError('JSON格式错误，请检查批量查询配置');
                } else {
                    showError(error.message);
                }
            } finally {
                hideLoading();
            }
        });

        document.getElementById('updateForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            showLoading();

            try {
                const formData = {
                    data_id: document.getElementById('updateDataId').value,
                    cosmicid: document.getElementById('updateCosmicId').value,
                    firmcode: document.getElementById('updateFirmCode').value,
                    contract_code: document.getElementById('updateContractCode').value,
                    gnyhxq: document.getElementById('updateGnyhxq').value || null,
                    gngc: document.getElementById('updateGngc').value || null,
                    zgcms: document.getElementById('updateZgcms').value || null
                };

                const result = await apiCall('/update', 'POST', formData);
                showResults(result, '更新结果');
                document.getElementById('updateForm').reset();
            } catch (error) {
                showError(error.message);
            } finally {
                hideLoading();
            }
        });

        document.getElementById('deleteForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            if (!confirm('确定要删除这些数据吗？此操作不可撤销！')) {
                return;
            }

            showLoading();

            try {
                const dataIds = document.getElementById('deleteDataIds').value
                    .split('\n')
                    .map(id => id.trim())
                    .filter(id => id.length > 0);

                if (dataIds.length === 0) {
                    throw new Error('请输入至少一个数据ID');
                }

                const result = await apiCall('/delete', 'POST', { data_ids: dataIds });
                showResults(result, '删除结果');
                document.getElementById('deleteForm').reset();
            } catch (error) {
                showError(error.message);
            } finally {
                hideLoading();
            }
        });

        document.getElementById('batchUpdateForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            showLoading();

            try {
                const batchData = JSON.parse(document.getElementById('batchUpdateData').value);
                const result = await apiCall('/batch_update', 'POST', { updates: batchData });
                showResults(result, '批量更新结果');
            } catch (error) {
                if (error instanceof SyntaxError) {
                    showError('JSON格式错误，请检查批量更新数据');
                } else {
                    showError(error.message);
                }
            } finally {
                hideLoading();
            }
        });

        document.getElementById('incrementalUpdateForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            showLoading();

            try {
                const result = await apiCall('/incremental_update', 'POST');
                showResults(result, '增量更新结果');
            } catch (error) {
                showError(error.message);
            } finally {
                hideLoading();
            }
        });

        document.getElementById('initializeForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            if (!confirm('确定要重新初始化系统吗？这将清除所有缓存数据！')) {
                return;
            }

            showLoading();

            try {
                const result = await apiCall('/initialize', 'POST');
                showResults(result, '初始化结果');
            } catch (error) {
                showError(error.message);
            } finally {
                hideLoading();
            }
        });

        document.getElementById('thresholdForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            showLoading();

            try {
                const formData = {
                    thresholds: {
                        "功能用户需求": parseFloat(document.getElementById('thresholdGnyhxq').value),
                        "功能过程": parseFloat(document.getElementById('thresholdGngc').value),
                        "子过程描述": parseFloat(document.getElementById('thresholdZgcms').value)
                    },
                    save_to_file: true
                };

                const result = await apiCall('/update_thresholds', 'POST', formData);
                showResults(result, '阈值更新结果');
                loadCurrentThresholds(); // 重新加载当前配置
            } catch (error) {
                showError(error.message);
            } finally {
                hideLoading();
            }
        });

        // 格式化JSON函数
        function formatBatchJson() {
            const textarea = document.getElementById('batchQueries');
            try {
                const parsed = JSON.parse(textarea.value);
                textarea.value = JSON.stringify(parsed, null, 2);
            } catch (error) {
                alert('JSON格式错误，无法格式化');
            }
        }

        function formatBatchUpdateJson() {
            const textarea = document.getElementById('batchUpdateData');
            try {
                const parsed = JSON.parse(textarea.value);
                textarea.value = JSON.stringify(parsed, null, 2);
            } catch (error) {
                alert('JSON格式错误，无法格式化');
            }
        }

        // 加载当前阈值配置
        async function loadCurrentThresholds() {
            try {
                const result = await apiCall('/get_thresholds', 'GET');
                document.getElementById('currentThresholds').innerHTML = `
                    <div class="stats stats-vertical lg:stats-horizontal shadow">
                        <div class="stat">
                            <div class="stat-title">功能用户需求</div>
                            <div class="stat-value text-primary">${result.thresholds["功能用户需求"] || 'N/A'}</div>
                        </div>
                        <div class="stat">
                            <div class="stat-title">功能过程</div>
                            <div class="stat-value text-secondary">${result.thresholds["功能过程"] || 'N/A'}</div>
                        </div>
                        <div class="stat">
                            <div class="stat-title">子过程描述</div>
                            <div class="stat-value text-accent">${result.thresholds["子过程描述"] || 'N/A'}</div>
                        </div>
                    </div>
                `;

                // 更新表单中的值
                document.getElementById('thresholdGnyhxq').value = result.thresholds["功能用户需求"] || 0.85;
                document.getElementById('thresholdGngc').value = result.thresholds["功能过程"] || 0.90;
                document.getElementById('thresholdZgcms').value = result.thresholds["子过程描述"] || 0.88;
            } catch (error) {
                console.error('加载阈值配置失败:', error);
                document.getElementById('currentThresholds').innerHTML = `
                    <div class="alert alert-warning">
                        <span>无法加载当前配置</span>
                    </div>
                `;
            }
        }

        // 检查系统状态
        async function checkSystemStatus() {
            try {
                const result = await apiCall('/health', 'GET');
                const statusElement = document.getElementById('systemStatus');
                if (result.status === 'healthy') {
                    statusElement.innerHTML = `
                        <div class="alert alert-success">
                            <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <div>
                                <h3 class="font-bold">系统运行正常</h3>
                                <div class="text-xs">数据库连接: ${result.database_status || '正常'}</div>
                                <div class="text-xs">模型状态: ${result.model_status || '正常'}</div>
                                <div class="text-xs">缓存状态: ${result.cache_status || '正常'}</div>
                            </div>
                        </div>
                    `;
                } else {
                    statusElement.innerHTML = `
                        <div class="alert alert-error">
                            <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <span>系统状态异常，请检查服务</span>
                        </div>
                    `;
                }
            } catch (error) {
                document.getElementById('systemStatus').innerHTML = `
                    <div class="alert alert-warning">
                        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                        </svg>
                        <span>无法连接到API服务</span>
                    </div>
                `;
            }
        }

                // 定时器相关函数
        async function getTimerStatus() {
            try {
                const response = await apiCall('/timer/status', 'GET');
                return response;
            } catch (error) {
                console.error('获取定时器状态失败:', error);
                throw error;
            }
        }

        function updateTimerStatusUI(status) {
            const enabledElement = document.getElementById('timerEnabledStatus');
            const runningElement = document.getElementById('timerRunningStatus');
            const intervalElement = document.getElementById('timerInterval');
            const enabledCheckbox = document.getElementById('timerEnabled');
            const intervalInput = document.getElementById('timerIntervalInput');

            if (enabledElement) {
                enabledElement.textContent = status.enabled ? '已启用' : '已禁用';
                enabledElement.className = `stat-value text-lg ${status.enabled ? 'text-success' : 'text-error'}`;
            }

            if (runningElement) {
                runningElement.textContent = status.running ? '运行中' : '已停止';
                runningElement.className = `stat-value text-lg ${status.running ? 'text-success' : 'text-warning'}`;
            }

            if (intervalElement) {
                intervalElement.textContent = `${status.interval}秒`;
            }

            if (enabledCheckbox) {
                enabledCheckbox.checked = status.enabled;
            }

            if (intervalInput) {
                intervalInput.value = status.interval;
            }
        }

        async function updateTimerConfig(enable, interval) {
            try {
                const data = {};
                if (enable !== null) data.enable = enable;
                if (interval !== null) data.interval = interval;

                const response = await apiCall('/timer/config', 'POST', data);
                return response;
            } catch (error) {
                console.error('更新定时器配置失败:', error);
                throw error;
            }
        }

        async function startTimer() {
            try {
                // 使用 /timer/config 接口启动定时器
                const response = await apiCall('/timer/config', 'POST', { enable: true });
                await refreshTimerStatus();
                return response;
            } catch (error) {
                console.error('启动定时器失败:', error);
                throw error;
            }
        }

        async function stopTimer() {
            try {
                // 使用 /timer/config 接口停止定时器
                const response = await apiCall('/timer/config', 'POST', { enable: false });
                await refreshTimerStatus();
                return response;
            } catch (error) {
                console.error('停止定时器失败:', error);
                throw error;
            }
        }

        async function refreshTimerStatus() {
            try {
                const status = await getTimerStatus();
                updateTimerStatusUI(status);
            } catch (error) {
                console.error('刷新定时器状态失败:', error);
            }
        }

                // 定时器配置表单提交
        document.getElementById('timerConfigForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const submitBtn = e.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;

            try {
                submitBtn.innerHTML = '<div class="loading-spinner"></div>应用中...';
                submitBtn.disabled = true;

                const enabled = document.getElementById('timerEnabled').checked;
                const interval = parseInt(document.getElementById('timerIntervalInput').value);

                if (interval < 60) {
                    throw new Error('更新间隔不能少于60秒');
                }

                const result = await updateTimerConfig(enabled, interval);

                document.getElementById('results').innerHTML = `
                    <div class="alert alert-success">
                        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span>定时器配置更新成功！</span>
                    </div>
                    <div class="json-viewer">${formatJSON(result)}</div>
                `;

                await refreshTimerStatus();

            } catch (error) {
                document.getElementById('results').innerHTML = `
                    <div class="alert alert-error">
                        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span>配置更新失败: ${error.message}</span>
                    </div>
                `;
            } finally {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        });

        // 启动定时器按钮
        document.getElementById('startTimerBtn').addEventListener('click', async function() {
            const btn = this;
            const originalText = btn.innerHTML;

            try {
                btn.innerHTML = '<div class="loading-spinner"></div>启动中...';
                btn.disabled = true;

                const result = await startTimer();

                document.getElementById('results').innerHTML = `
                    <div class="alert alert-success">
                        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span>定时器启动成功！</span>
                    </div>
                    <div class="json-viewer">${formatJSON(result)}</div>
                `;

            } catch (error) {
                document.getElementById('results').innerHTML = `
                    <div class="alert alert-error">
                        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span>启动定时器失败: ${error.message}</span>
                    </div>
                `;
            } finally {
                btn.innerHTML = originalText;
                btn.disabled = false;
            }
        });

        // 停止定时器按钮
        document.getElementById('stopTimerBtn').addEventListener('click', async function() {
            const btn = this;
            const originalText = btn.innerHTML;

            try {
                btn.innerHTML = '<div class="loading-spinner"></div>停止中...';
                btn.disabled = true;

                const result = await stopTimer();

                document.getElementById('results').innerHTML = `
                    <div class="alert alert-success">
                        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span>定时器停止成功！</span>
                    </div>
                    <div class="json-viewer">${formatJSON(result)}</div>
                `;

            } catch (error) {
                document.getElementById('results').innerHTML = `
                    <div class="alert alert-error">
                        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span>停止定时器失败: ${error.message}</span>
                    </div>
                `;
            } finally {
                btn.innerHTML = originalText;
                btn.disabled = false;
            }
        });

        // 刷新定时器状态按钮
        document.getElementById('refreshTimerStatusBtn').addEventListener('click', async function() {
            const btn = this;
            const originalText = btn.innerHTML;

            try {
                btn.innerHTML = '<div class="loading-spinner"></div>刷新中...';
                btn.disabled = true;

                await refreshTimerStatus();

            } catch (error) {
                document.getElementById('results').innerHTML = `
                    <div class="alert alert-error">
                        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span>刷新状态失败: ${error.message}</span>
                    </div>
                `;
            } finally {
                btn.innerHTML = originalText;
                btn.disabled = false;
            }
        });

                // 多字段内部相似度分析
        // 多字段内部相似度分析
        async function analyzeMultiFieldSimilarity(cosmicId, fields) {
            try {
                const response = await apiCall('/analyze_multi_field_similarity', 'POST', {
                    cosmicid: cosmicId,
                    fields: fields
                });
                return response;
            } catch (error) {
                console.error('多字段相似度分析失败:', error);
                throw error;
            }
        }

        // 格式化多字段相似度分析结果
        function formatMultiFieldSimilarityResult(result) {
            if (result.status === 'error') {
                return `<div class="text-red-600">错误: ${result.message}</div>`;
            }

            let html = `
                <div class="space-y-6">
                    <div class="bg-blue-50 p-4 rounded-lg">
                        <h3 class="font-semibold text-blue-800 mb-2">分析概要</h3>
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                            <div><span class="font-medium">Cosmic ID:</span> ${result.cosmicid}</div>
                            <div><span class="font-medium">分析字段数:</span> ${result.summary.total_fields}</div>
                            <div><span class="font-medium">有高相似度的字段:</span>
                                <span class="${result.summary.fields_with_high_similarity > 0 ? 'text-red-600 font-bold' : 'text-green-600'}">
                                    ${result.summary.fields_with_high_similarity}
                                </span>
                            </div>
                            <div><span class="font-medium">总高相似度对数:</span>
                                <span class="${result.summary.total_high_similarity_pairs > 0 ? 'text-red-600 font-bold' : 'text-green-600'}">
                                    ${result.summary.total_high_similarity_pairs}
                                </span>
                            </div>
                        </div>
                    </div>
            `;

            // 显示每个字段的分析结果
            for (const [fieldName, fieldResult] of Object.entries(result.field_results)) {
                const hasHighSimilarity = fieldResult.has_high_similarity;
                const borderColor = hasHighSimilarity ? 'border-red-200' : 'border-gray-200';
                const bgColor = hasHighSimilarity ? 'bg-red-50' : 'bg-gray-50';

                html += `
                    <div class="${bgColor} ${borderColor} border rounded-lg p-4">
                        <h3 class="font-semibold text-gray-800 mb-2">
                            ${fieldName} (${fieldResult.query_type}) - 阈值: ${(fieldResult.threshold * 100).toFixed(0)}%
                        </h3>
                        <div class="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm mb-3">
                            <div><span class="font-medium">去重后内容数:</span> ${fieldResult.total_unique_contents}</div>
                            <div><span class="font-medium">高相似度对数:</span>
                                <span class="${fieldResult.high_similarity_pairs > 0 ? 'text-red-600 font-bold' : 'text-green-600'}">
                                    ${fieldResult.high_similarity_pairs}
                                </span>
                            </div>
                            <div><span class="font-medium">状态:</span>
                                <span class="${hasHighSimilarity ? 'text-red-600' : 'text-green-600'} font-medium">
                                    ${hasHighSimilarity ? '发现高相似度' : '无高相似度'}
                                </span>
                            </div>
                        </div>
                `;

                if (fieldResult.total_unique_contents < 2) {
                    html += `<div class="text-gray-600 text-sm">${fieldResult.message}</div>`;
                } else {
                    // 显示去重后的内容
                    html += `
                        <div class="bg-white p-3 rounded border mb-3">
                            <h4 class="font-medium text-gray-700 mb-2">去重后的内容 (${fieldResult.unique_contents.length}条)</h4>
                            <div class="space-y-1 max-h-32 overflow-y-auto text-sm">
                    `;

                    fieldResult.unique_contents.forEach((content, index) => {
                        html += `<div class="p-2 bg-gray-50 rounded"><span class="font-medium">${index + 1}.</span> ${content}</div>`;
                    });

                    html += `</div></div>`;

                    // 显示相似度对比结果（只显示高相似度的）
                    const highSimilarityPairs = fieldResult.similarity_pairs.filter(pair => pair.exceeds_threshold);
                    if (highSimilarityPairs.length > 0) {
                        html += `
                            <div class="bg-white p-3 rounded border">
                                <h4 class="font-medium text-red-700 mb-2">高相似度对比 (${highSimilarityPairs.length}对)</h4>
                                <div class="space-y-2 max-h-40 overflow-y-auto">
                        `;

                        highSimilarityPairs.forEach((pair, index) => {
                            html += `
                                <div class="bg-red-50 border border-red-200 rounded p-2">
                                    <div class="flex justify-between items-center mb-1">
                                        <span class="font-medium text-red-800">高相似度对 ${index + 1}</span>
                                        <span class="bg-red-100 text-red-800 px-2 py-1 rounded text-sm font-medium">
                                            ${pair.similarity_percentage.toFixed(2)}% ⚠️
                                        </span>
                                    </div>
                                    <div class="text-sm space-y-1">
                                        <div><span class="font-medium">内容1:</span> ${pair.content_1}</div>
                                        <div><span class="font-medium">内容2:</span> ${pair.content_2}</div>
                                    </div>
                                </div>
                            `;
                        });

                        html += `</div></div>`;
                    }
                }

                html += `</div>`;
            }

            html += `</div>`;
            return html;
        }

        // 多字段内部相似度分析表单提交
        document.getElementById('multiFieldSimilarityForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const cosmicId = document.getElementById('multiFieldCosmicId').value.trim();

            // 获取选中的字段
            const selectedFields = [];
            if (document.getElementById('field_gnyhxq').checked) selectedFields.push('gnyhxq');
            if (document.getElementById('field_gngc').checked) selectedFields.push('gngc');
            if (document.getElementById('field_zgcms').checked) selectedFields.push('zgcms');

            if (!cosmicId) {
                alert('请输入Cosmic ID');
                return;
            }

            if (selectedFields.length === 0) {
                alert('请至少选择一个字段进行分析');
                return;
            }

            try {
                showLoading('正在分析多字段内部相似度...');
                const result = await analyzeMultiFieldSimilarity(cosmicId, selectedFields);
                const formattedResult = formatMultiFieldSimilarityResult(result);
                showResults(formattedResult, '多字段内部相似度分析结果');
            } catch (error) {
                showError('分析失败: ' + error.message);
            } finally {
                hideLoading();
            }
        });


        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 默认显示搜索标签页
            showTab('search');

            // 加载当前阈值配置
            loadCurrentThresholds();

            // 检查系统状态
            checkSystemStatus();

            // 初始化定时器状态
            refreshTimerStatus();

        });

        // 导出结果功能
        function exportResults() {
            if (!currentResults) {
                alert('没有可导出的结果');
                return;
            }

            const dataStr = JSON.stringify(currentResults, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            const url = URL.createObjectURL(dataBlob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `search_results_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`;
            link.click();
            URL.revokeObjectURL(url);
        }

        // 清空结果
        function clearResults() {
            document.getElementById('results-content').innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fas fa-search text-4xl mb-4"></i>
                    <p>执行API调用后，结果将在这里显示</p>
                </div>
            `;
            currentResults = null;
        }

        // 在现有的 JavaScript 代码中添加或修改 cosmicAnalysisForm 的处理
        document.getElementById('cosmicAnalysisForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const pswfinstid = document.getElementById('analysisCosmicId').value.trim();
            if (!pswfinstid) {
                showNotification('请输入pswfinstid', 'error');
                return;
            }

            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<div class="loading-spinner"></div>分析中...';
            submitBtn.disabled = true;

            try {
                const apiUrl = document.getElementById('apiBaseUrl').value || 'http://localhost:8000';
                const response = await fetch(`${apiUrl}/analyze_cosmic_similarity_by_pswfinstid`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ pswfinstid: pswfinstid })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || '请求失败');
                }

                const result = await response.json();
                displayCosmicSimilarityResults(result);
                showNotification('相似度分析完成', 'success');

            } catch (error) {
                console.error('相似度分析失败:', error);
                showNotification(`分析失败: ${error.message}`, 'error');
            } finally {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        });
    </script>
</body>
</html>